<template>
  <div></div>
</template>
<script lang="ts" setup>
import emptyMp3 from "@/assets/sound/empty.mp3";
import msgSoundMp3 from "@/assets/sound/msgSound.mp3";
import resultMp3 from "@/assets/sound/result.mp3";

import { SoundName } from "@/enums";
import { ElMessageBox } from "element-plus";

interface State {
  audio: HTMLAudioElement;
}

const props = defineProps({
  name: {
    type: String as PropType<SoundName>,
    default: SoundName.empty
  }
});

const state = reactive<State>({
  audio: new Audio(emptyMp3)
});
const setSound = () => {
  if (props.name == SoundName.msgSound) {
    state.audio = new Audio(msgSoundMp3);
  } else if (props.name == SoundName.result) {
    state.audio = new Audio(resultMp3);
  }
};
let show = ref(false);
const play = () => {
  state.audio.muted = true;
  const ctx = new AudioContext();
  const canAutoPlay = ctx.state === "running";
  ctx.close();
  if (canAutoPlay) {
    state.audio.muted = false;
    state.audio.currentTime = 0;
    state.audio.play();
  } else {
    if (show.value) {
      return;
    }
    ElMessageBox.confirm("允许播放声音", "提示", {
      confirmButtonText: "确认",
      showCancelButton: false,
      type: "warning",
      showClose: false
    }).then(() => {
      play();
    });
    show.value = true;
  }
};
const pause = () => {
  state.audio.pause();
};
const setVolume = (v: number) => {
  state.audio.volume = v;
};
onMounted(() => {
  setSound();
});
defineExpose({
  play,
  pause,
  setVolume
});
</script>
